<template>
  <div>
    <el-dialog
      v-el-drag-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form-item label="楼层名称" prop="floorName">
          <el-input v-model="dataForm.floorName"  placeholder="楼层名称只做为内部标识"></el-input>
        </el-form-item>
        <el-form-item label="首页模板" prop="templateId">
          <el-select v-model="dataForm.templateId" placeholder="请选择" value="">
            <el-option key="1" label="模板1" value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层图片" prop="img">
          <el-upload
            :class="{hide:hideUpload}"
            :action="this.$http.adornUrl(`/banner/uploadBanner?token=${this.$cookie.get('token')}`)"
            :limit="1"
            list-type="picture-card"
            :file-list="dataForm.img"
            :on-preview="handlePreview"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-exceed="onExceed">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="选择商品">
          <el-button @click="addOrUpdateHandle">选择商品</el-button>
          <div style="color: #909399;font-size: 10px;">选中商品将在首屏显示，已选择{{goodsList.length}}件,最多可选8款商品</div>
          <el-table v-if="goodsList.length !== 0"
            :data="goodsInfoList"
            border
            style="width: 100%">
            <el-table-column
              prop="img"
              label="商品图">
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  trigger="hover">
                  <img :src="scope.row.img" style="max-height: 100px;"/>
                  <img slot="reference" :src="scope.row.img" style="max-height: 50px;max-width: 130px">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              prop="goodsName"
              label="商品名">
            </el-table-column>
            <el-table-column
              prop="address"
              label="价格类型">
              <template slot-scope="scope">
                {{scope.row.address === 1 ?'兑换商城':'福利商城'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="goodsInventory"
              label="库存">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" v-if="isAuth('home:floor:remove')"  @click="deleteGoodsHandle(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="跳转类型" prop="jumpType">
          <el-row  style="display: flex;">
            <el-select v-model="dataForm.jumpType" placeholder="分类" value="" style="margin-right: 30px">
              <el-option label="商品分类" :value="0" ></el-option>
              <el-option label="外链" :value="3" ></el-option>
              <el-option label="专题" :value="5" ></el-option>
              <el-option label="无跳转" :value="6" ></el-option>
            </el-select>
            <el-input v-model="dataForm.url" placeholder="请输入跳转类型id或链接"></el-input>
          </el-row>
        </el-form-item>
        <el-form-item label="排序" prop="seq">
          <el-input v-model="dataForm.seq" placeholder="数值越大排序越靠前"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark"  type="textarea" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getGoodsList="getGoodsList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './goods-add-or-update'
  export default {
    data () {
      return {
        hideUpload: false,
        limitCount: 1,
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        addOrUpdateVisible: false,
        goodsList: [],
        goodsInfoList: [],
        dataForm: {
          id: 0,
          bannerType: '',
          remark: '',
          jumpType: '',
          imgName: '',
          imgPath: '',
          img: [],
          floorName: '',
          templateId: 1,
          seq: 0,
          url: ''
        },
        dataRule: {
          bannerType: [
            { required: true, message: '分类不能为空', trigger: 'blur' }
          ],
          imgName: [
            { required: true, message: '图片名称不能为空', trigger: 'blur' }
          ],
          imgPath: [
            { required: true, message: '图片路径不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      AddOrUpdate
    },
    methods: {
      getGoodsList (goodsList, goodsInfoList) {
        this.goodsList = goodsList
        this.goodsInfoList = goodsInfoList
      },
      // 图片预览
      handlePreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 1000
        })
        if (res.code === 0) {
          this.dataForm.img.push({name: 'tu', url: res.data})
        }
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        for (let i = 0; i < this.dataForm.img.length; i++) {
          let picc = this.dataForm.img[i]
          if (picc.url === file.url) {
            this.dataForm.img.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 1000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 1000
        })
      },
      init (id) {
        this.hideUpload = false
        Object.assign(this.$data, this.$options.data())
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/home/floor/getFloorById/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.bannerType = data.data.bannerType
                this.dataForm.remark = data.data.remark
                this.dataForm.jumpType = data.data.jumpType
                this.dataForm.floorName = data.data.floorName
                this.dataForm.templateId = data.data.templateId
                this.dataForm.url = data.data.url
                this.goodsList = []
                this.goodsInfoList = []
                let than = this
                data.data.urlData.split(',').map(
                  item => {
                    let id = Number.parseInt(item)
                    if (Number.isInteger(id)) {
                      this.getGoods(id).then(data => {
                        than.goodsList.push(id)
                        than.goodsInfoList.push({
                          'img': data.img,
                          'id': data.id,
                          'goodsName': data.goodsName,
                          'priceType': data.priceType,
                          'goodsInventory': data.goodsInventory
                        })
                      })
                    }
                  })
                this.dataForm.seq = data.data.seq
                this.dataForm.img.push({name: 'tu', url: `http://image.yilianbaihui.cn/consumer/${data.data.imgPath}/${data.data.imgName}`})
                this.hideUpload = true
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit: function () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/home/floor/${!this.dataForm.id ? 'add' : 'modifyFloorById'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'bannerType': this.dataForm.bannerType,
                'imgName': this.dataForm.img[0].url.substring(this.dataForm.img[0].url.lastIndexOf('/') + 1, this.dataForm.img[0].url.length),
                'imgPath': 'banner',
                'remark': this.dataForm.remark,
                'jumpType': this.dataForm.jumpType,
                'floorName': this.dataForm.floorName,
                'templateId': this.dataForm.templateId,
                'seq': this.dataForm.seq,
                'urlData': this.goodsList.join(','),
                'url': this.dataForm.url
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(this.goodsList, this.goodsInfoList)
        })
      },
      deleteGoodsHandle (id) {
        this.goodsList.splice(this.goodsList.indexOf(id), 1)
        for (let i = 0; i < this.goodsInfoList.length; i++) {
          if (this.goodsInfoList[i].id === id) {
            this.goodsInfoList.splice(i, 1)
            i--
          }
        }
      },
      async getGoods (id) {
        let info
        try {
          await this.$http({
            url: this.$http.adornUrl(`/goods/getGoodsById/${id}`),
            method: 'post'
          }).then(({data}) => {
            if (data && data.code === 0) {
              info = data.data
            }
          })
        } catch (e) {
          console.log(e)
        }
        return info
      }
    }
  }
</script>
<style>
  .hide .el-upload--picture-card {  display: none; }
</style>
